import { getCartList, updateCartGoods, sleDel } from '@/api/cart'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList (state, newValue) {
      state.cartList = newValue
    },
    toggleChecked (state, goodsId) {
      const goods = state.cartList.find(e => {
        if (e.goods_id === goodsId) {
          return true
        }
        return false
      })
      goods.isChecked = !goods.isChecked
    },
    toggleAllChecked (state, flag) {
      state.cartList.forEach(e => { e.isChecked = flag })
    },
    updateCartGoods (state, obj) {
      const goods = state.cartList.find(e => {
        if (e.goods_id === obj.goods_id) {
          return true
        }
        return false
      })
      goods.goods_num = obj.goods_num
    }
  },
  actions: {
    async getCartList (context) {
      const { data: { list } } = await getCartList()
      list.forEach(e => {
        e.isChecked = true
      })
      context.commit('setCartList', list)
    },
    async updateCartGoods (context, obj) {
      const { goods_num: goodsNum, goods_id: goodsId, goods_sku_id: goodsSkuId } = obj
      const { status } = await updateCartGoods(goodsId, goodsNum, goodsSkuId)
      if (status === 200) {
        context.commit('updateCartGoods', obj)
      }
    },
    async sleDel (context) {
      if (context.getters.selectCartList.length === 0) return
      const cartsId = context.getters.selectCartList.map(e => {
        return e.id
      })
      await sleDel(cartsId)
      context.dispatch('getCartList')
    }
  },
  getters: {
    // 购物车商品数量累加和
    cartTotal (state) {
      return state.cartList.reduce((pre, curr) => {
        return pre + curr.goods_num
      }, 0)
    },
    // 选中的商品项
    selectCartList (state) {
      return state.cartList.filter(e => {
        return e.isChecked
      })
    },
    // 选中的商品总数
    selCount (state, getters) {
      return getters.selectCartList.reduce((pre, curr) => {
        return pre + curr.goods_num
      }, 0)
    },
    // 选中的总价
    selPrice (state, getters) {
      return getters.selectCartList.reduce((pre, curr) => {
        return pre + curr.goods_num * curr.goods.goods_price_min
      }, 0)
    },
    // 是否全选
    isAllChecked (state, getters) {
      return state.cartList.length === getters.selectCartList.length
    }
  }
}
